#include "kdcreadfileinfojob.h"

#include <jobs/kdcmplayermencoderjob.h>

#include <KLocale>

KDCReadFileInfoJob::KDCReadFileInfoJob( const QString& file, QObject *parent )
	: KDCCompositeJob( parent ), p_fileName( file ), p_video( NULL )
{
	KDCMPlayerMencoderJob *job = new KDCMPlayerMencoderJob( KDCMPlayerMencoderJob::MPlayer, this );
	job->addArgument( "-noautosub" );
	job->addArgument( "-channels", "6" );
	job->addArgument( "-vo", "null" );
	job->addArgument( "-ao", "null" );
	job->addArgument( "-identify" );
	job->addArgument( "-frames", "1" );
	job->setFile( file );
	connect( job, SIGNAL( foundAudioStream( int ) ), this, SLOT( slotFoundAudioStream( int ) ) );
	addSubjob( job );
	setTotalAmount( KJob::Bytes, 100 );
}

KDCReadFileInfoJob::~KDCReadFileInfoJob()
{

}

void KDCReadFileInfoJob::start()
{
	emit description( this, i18n("Reading file info..."), qMakePair( p_fileName ,QString() ) );
	subjobs().first()->start();
}

KDCVideoMetaData* KDCReadFileInfoJob::video() const
{
	return p_video;
}

const QList<KDCAudioMetaData*>& KDCReadFileInfoJob::audio() const
{
	return p_audio;
}
	
void KDCReadFileInfoJob::slotFoundAudioStream( int id )
{
	p_audioID.append( id );
}

void KDCReadFileInfoJob::slotResult( KJob *job )
{
	removeSubjob( job );
	if ( job->error() )
	{
		setError( job->error() );
		setErrorText( job->errorText() );
		emitResult();
	}
	else
	{
		KDCMPlayerMencoderJob *tmp = static_cast<KDCMPlayerMencoderJob*>( job );
		KDCMPlayerFileInfo info = tmp->info();
		if ( !p_video && info.vID != -1 && info.width != -1 )
			p_video = new KDCVideoMetaData( info.demuxer, info.vFormat, info.width, info.height, info.vBitrate, info.fps, info.length, info.ar );
		if ( !p_audioID.isEmpty() && p_video )
		{
			p_audio.append( new KDCAudioMetaData( p_audioID.first(), info.aFormat, info.nch, info.srate, info.aBitrate, info.length ) );
			p_audioID.removeFirst();
			if ( !p_audioID.isEmpty() )
			{
				tmp = new KDCMPlayerMencoderJob( KDCMPlayerMencoderJob::MPlayer, this );
				tmp->addArgument( "-noautosub" );
				tmp->addArgument( "-aid", QString::number( p_audioID.first() ) );
				tmp->addArgument( "-channels", "6" );
				tmp->addArgument( "-vo", "null" );
				tmp->addArgument( "-ao", "null" );
				tmp->addArgument( "-identify" );
				tmp->addArgument( "-frames", "1" );
				tmp->setFile( p_fileName );
				addSubjob( tmp );
				tmp->start();
			}
			else
			{
				setPercent( 100 );
				emitResult();
			}
		}
		else
		{
			setPercent( 100 );
			emitResult();
		}
	}
}
